package com.framework.network.interceptor

import android.content.Context
import com.framework.network.annotations.getRetrofitMethod
import com.framework.network.annotations.getSource
import com.framework.network.annotations.getSourceParameter
import com.framework.network.manager.NetworkManager
import com.framework.network.utils.JsonToMapUtil
import okhttp3.*
import okio.Buffer
import java.nio.charset.Charset

/**
 * @Description:设置请求头参数
 * @Author: you
 */
class HeadParamsInterceptor(private val context: Context) : Interceptor {
    private val utf8 = Charset.forName("UTF-8")

    override fun intercept(chain: Interceptor.Chain): Response {
        //先获取source的注解
        var source = ""
        getRetrofitMethod(chain.request())?.let {
            val sourceMethod = getSource(it)
            if (sourceMethod != null) {
                source = getSourceParameter(sourceMethod)
            }
        }
        //接口请求的参数
//        val requestParams = getRequestParams(chain)

        val mBuilder = chain.request().newBuilder()
        //添加头部公参数
        NetworkManager.getInstance().create().headCommonMap?.forEach {
            mBuilder.addHeader(it.key, it.value.toString())
        }
        //添加头部动态参数
        NetworkManager.getInstance().create().mOnAddHeadDynamicParamsListener?.let {
            val mHeadDynamicParams = it.onHeadDynamicParams(chain.request())
            if (mHeadDynamicParams.size > 0) {
                mHeadDynamicParams.forEach { maps ->
                    mBuilder.addHeader(maps.key, maps.value.toString())
                }
            }
        }
        val request = mBuilder.build()
        return chain.proceed(request)
    }

    /**
     * 获取请求时的参数
     */
    private fun getRequestParams(chain: Interceptor.Chain): HashMap<String, Any> {
        val maps = HashMap<String, Any>()
        val request = chain.request()
        when (request.method) {
            "GET" -> {
                val httpUrl = request.url.newBuilder().build()
                httpUrl.queryParameterNames.forEach { key ->
                    val value = httpUrl.queryParameter(key)
                    if (value.isNullOrBlank().not()) {
                        maps[key] = value ?: ""
                    }
                }
            }
            "POST" -> {
                val requestParamsStr = getRequestParams(request)
                if(requestParamsStr.isNullOrBlank().not()){
                    JsonToMapUtil.gsonToMap(requestParamsStr)?.toMap()?.let {
                        maps.putAll(it)
                    }
                }
            }
        }
        return maps
    }

    /**
     * 获取请求参数
     */
    private fun getRequestParams(request: Request): String {
        var paramsStr = ""
        runCatching {
            var charset = utf8
            val requestBody = request.body
            if (requestBody != null) {
                val buffer = Buffer()
                requestBody.writeTo(buffer)
                val contentType = requestBody.contentType()
                contentType?.let {
                    charset = contentType.charset(utf8)
                }
                paramsStr = buffer.readString(charset)
            }
        }.onFailure {
            paramsStr = ""
        }
        return paramsStr
    }
}